

import multiprocessing
import Queue
import threading
import time
import hashlib

speck = None
running = False
stopFlag = False


def beamProcess(queue = None):
    from beam import Beam
    import pyglet
    
    beam = Beam()

    def update(dt):
        try:
            message = queue.get(block = False)
            if message['command'] == "set speck":
                beam.speck = message['speck']
            elif message['command'] == "stop":
                pyglet.app.exit()
            beam.invalid = True
        except Queue.Empty:
            pass
        beam.invalid = True
        
    pyglet.clock.schedule_interval(update, 1.0 / 60.0)
    pyglet.app.run()


def beamThread():
    global running
    queue = multiprocessing.Queue()
    p = multiprocessing.Process(target = beamProcess, args = (queue,))
    p.start()
    running = True
    lastHash = 0
    while p.is_alive():
        try:
            if stopFlag:
                queue.put({'command': 'stop'})
                return
            if hashlib.sha1(speck.r).hexdigest() != lastHash:
                queue.put({'command': 'set speck', 'speck': speck})
                lastHash = hashlib.sha1(speck.r).hexdigest()
            else:
                time.sleep(1.0 / 30.0)
        except:
            break
    running = False


def start():
    threading.Thread(target = beamThread).start()
    while not running:
        time.sleep(0.01)
    

def stop():
    global stopFlag
    stopFlag  = True
        
    
    








